package com.shop.web.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shop.domain.Product;
import com.shop.service.ProductService;

public class CartServlet2 extends HttpServlet {

	private static final long serialVersionUID = 7715865743257658440L;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String[] items = req.getParameterValues("getAll");
		System.out.println(items);
		for(String s:items){
			ProductService service = new ProductService();
			Map<Product, Integer> cart = (Map<Product, Integer>) req.getSession().getAttribute("cart");
//		String id=items[i].toString();
		System.out.println(s);
		Product product = service.findProduct(s);
		if (cart == null) {
			cart = new HashMap<Product, Integer>();
		}
		
		
		if (cart.containsKey(product)) {
			int num = cart.get(product);
			cart.put(product, num+1);
			System.out.println(num);
		}else {
			cart.put(product, 1);
			System.out.println(cart.get(product));
		}
		req.getSession().setAttribute("cart", cart);
		}
		req.getRequestDispatcher("ListProductServlet").forward(req, resp);
		
	}
}
